<template>
  <div>
    <!-- 定义一个输入框，不可编辑，focus时触发事件,打开一个dialog -->
    <a-input readOnly :value="value" @click="handleFocus" :placeholder="$t('columns.placeholder')"></a-input>
    <!-- 定义一个dialog -->
    <a-modal :title="$t('title')" width="69.9%" v-model="visible" @ok="handleOk" @cancel="handleCancel">
      <div class="map-tools">
        <a-radio-group v-model="mode" button-style="solid">
          <a-radio-button value="DRAW">
            {{ $t('modes.drawing') }}
          </a-radio-button>
          <a-radio-button value="INTERACT">
            {{ $t('modes.editing') }}
          </a-radio-button>
        </a-radio-group>

        <div style="margin-left: 20px;">
          <a-button v-if="mode== 'INTERACT'" type="danger" @click="handleRemove">
            <a-icon type="delete" />
          </a-button>
        </div>
      </div>
     
      <div id="edit_fence_map" style="width: 100%; height: 520px;"></div>
    </a-modal>
  </div>
</template>

<script>
import _ from 'lodash';
function isScriptAlreadyLoaded(srcCheck) {
    var scripts = document.getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src.includes(srcCheck)) {
            return true; // 如果找到匹配的src，返回true
        }
    }
    return false; // 如果没有找到匹配的src，返回false
}

// 辅助函数：检查两个点是否相近
function arePointsNear(point1, point2, tolerance) {
  return google.maps.geometry.spherical.computeDistanceBetween(point1, point2) <= tolerance;
};

export default {
  name: "EditFence",
  data() {
    return {
      visible: false,
      title: "圆形",
      map: null,
      mode: 'DRAW',
      fenceObj: null,
      path:[], // 用于存储多边形顶点的数组
      firstPoint:null // 用于存储第一个点的变量
    };
  },
  props: {
    area: {
      type: [Object, Array],
      default: ()=> ({}),
    },
    shapeType: {
      type: String,
      default: "circle",
    },
    center: {
      type: Object,
      default: ()=> ({}),
    },
  },
  computed: {
    value() {
      if (this.shapeType === 'circle' && !_.isEmpty(this.area)) {
        // 获取矩形顶点坐标
        const x = this.area.latitude.toFixed(6);
        const y = this.area.longitude.toFixed(6);
        const r = this.area.radius.toFixed(6);
        return `(${x},${y},${r})`;
      }
      if (this.shapeType === 'polygon' && !_.isEmpty(this.area)) {
        // 获取多边形顶点坐标
        const value = this.area.map((item) => {
          const lat = item.latitude.toFixed(6);
          const lng = item.longitude.toFixed(6);
          return `(${lat},${lng})`;
        }).join(";");
        return value;
      }
    },
  },
  watch:{
    mode:{
      handler(val){
        if(val == "DRAW"){
          this.fenceObj.setDraggable(false);
          this.fenceObj.setEditable(false);
        }
        if(val == "INTERACT"){
          this.fenceObj.setDraggable(true);
          this.fenceObj.setEditable(true);
        }
      },
    }
  },
  methods: {
    handleRemove() {
      console.log("handleRemove---------:", this.fenceObj);
      if(this.shapeType == "circle"){
        this.fenceObj.setCenter(null);
        this.fenceObj.setRadius(null);
      }
      if(this.shapeType == "polygon"){
        this.fenceObj.setPath([]);
        this.path = []; // 用于存储多边形顶点的数组
        this.firstPoint = null; // 用于存储第一个点的变量
      }
    },
    handleFocus() {
      this.visible = true;
      this.showMap();
    },
    handleOk() {
      if(this.shapeType == "circle"){
        const center = this.fenceObj.getCenter();
        const radius = this.fenceObj.getRadius();
        if(!center || !radius){
          this.$emit('update:fence', null);
        }else{
          const x = center.lat();
          const y = center.lng();
          const r = radius;
          const circle = {
            lat: x,
            lng: y,
            radius: r
          }
          this.$emit('update:fence', circle);
        }
      }

      if(this.shapeType == "polygon"){
        const paths = this.fenceObj.getPath().getArray();
        console.log("handleOk-----------:", paths);
        if(paths.length == 0){
          this.$emit('update:fence', null);
        }else{
          const x = paths[0].lat();
          const y = paths[0].lng();
          const path = paths.map(item=>{
            const lat = item.lat();
            const lng = item.lng();
            return {
              lat: lat,
              lng: lng
            }
          });
          const polygon = {
            lat: x,
            lng: y,
            paths: path
          }
          this.$emit('update:fence', polygon);
        }
      }
      this.visible = false;
    },
    handleCancel() {
      this.visible = false;
    },
    async showMap(){
      await this.loadScript(); // 使用 await 等待脚本加载完成
      if(!this.map){
        let point;
        if(_.isEmpty(this.center)){
          point = await this.getPoint();
        }else{
          point = this.center;
        }
        this.$nextTick(() => {
          this.initMap(point);
        })
      }
    },
    async loadScript() {
      const KEY = window._CONFIG['gMapKey'];
      const scriptSrc = `https://maps.googleapis.com/maps/api/js?libraries=geometry&key=${KEY}`;
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); // 如果脚本已经加载，则直接解决 Promise
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve(); // 脚本加载完成后解决 Promise
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); // 脚本加载出错时拒绝 Promise
          };
          document.body.appendChild(script);
        }
      });
    },
    initMap(point) { 
      console.log('初始化地图-----------------:');
      const center = new google.maps.LatLng(point.latitude, point.longitude);
      this.map = new google.maps.Map(document.getElementById('edit_fence_map'), {
          zoom: 12, // 设置地图缩放级别
          center: center, // 设置地图中心点坐标
      });
      if(this.shapeType == "circle"){
        this.drawCircle();
      }
      if(this.shapeType == "polygon"){
        this.drawPolygon();
      }
    },
    drawCircle() {
      console.log('绘制圆形-----------------:');
      this.fenceObj = new google.maps.Circle({
        strokeColor: '#3777FF',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: '#3777FF',
        fillOpacity: 0.6,
        map: this.map
      });
      let isDrawing = false; // 是否正在绘制圆
      if(!_.isEmpty(this.area)){
        const obj = this.area;
        this.fenceObj.setCenter(new google.maps.LatLng(obj.latitude, obj.longitude));
        this.fenceObj.setRadius(obj.radius);
      }

      google.maps.event.addListener(this.fenceObj, 'mousemove', () => {
        // TODO 移到圆内缩小圆
        if(isDrawing){
          const currentRadius = this.fenceObj.getRadius();
          const newRadius = Math.max(10, currentRadius - 10); // 10是每次缩小的量，可以根据需要调整
          this.fenceObj.setRadius(newRadius);
        }
      });

      google.maps.event.addListener(this.fenceObj, 'click', () => {
        // TODO 移到圆内缩小圆
        if(isDrawing){
          isDrawing = false; // 结束绘制
        }
      });

      // 绑定鼠标移动事件，用于动态更新半径并绘制圆
      google.maps.event.addListener(this.map, 'mousemove', (event) => {
        if (isDrawing) {
          // 计算半径（两点之间的距离）
          const radius = google.maps.geometry.spherical.computeDistanceBetween(this.fenceObj.getCenter(), event.latLng);
          this.fenceObj.setRadius(radius);
        }
      });

      // 绑定点击事件，用于设置圆心
      google.maps.event.addListener(this.map, 'click', (event) => {
        if(this.fenceObj.getCenter()){
          return;
        }
        if(isDrawing){
          isDrawing = false; // 结束绘制
        }else{
          this.fenceObj.setCenter(event.latLng);
          isDrawing = true; // 开始绘制
        }
      });
    },
    drawPolygon(){
      console.log('绘制多边形-----------------:');
      let isDrawing = false; // 是否正在绘制圆
      const pointTolerance = 10; // 定义点之间的容忍距离（单位可能是米，取决于地图的投影）
  
      this.fenceObj = new google.maps.Polygon({
        strokeColor: '#3777FF',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: '#3777FF',
        fillOpacity: 0.6,
        map: this.map
      });

      if(!_.isEmpty(this.area)){
        console.log("drawPolygon---------:", this.area);
        const objarr = this.area;
        this.firstPoint = new google.maps.LatLng(objarr[0].latitude,objarr[0].longitude);
        objarr.forEach((item)=>{
          const lat = item.latitude;
          const lng = item.longitude;
          this.path.push(new google.maps.LatLng(lat,lng));
        })
        this.fenceObj.setPath(this.path);
      }
     
      google.maps.event.addListener(this.map, 'click', (event) => {
        console.log("google.maps.event.addListener----:", event.latLng);
        //TODO 记录多边形的点，如果我在同一个点，点击两次且已经有两个点了，实现吸附效果，直接与第一个点连接在一起
        if (!isDrawing) {
          // 开始绘制多边形
          isDrawing = true;
          this.firstPoint = event.latLng; // 记录第一个点
          this.path.push(this.firstPoint); // 将第一个点添加到路径中
          this.fenceObj.setPath(this.path); // 设置多边形的路径
        } else {
          // 检查是否应该闭合多边形
          if (arePointsNear(this.firstPoint, event.latLng, pointTolerance)) {
            // 如果当前点击的点与第一个点相近，则闭合多边形
            isDrawing = false; // 结束绘制
            console.log('多边形已闭合');
          } else {
            // 否则，继续添加点到多边形
            this.path.push(event.latLng); // 将当前点添加到路径中
            this.fenceObj.setPath(this.path); // 更新多边形的路径
          }
        }
      });
    },
    //定义一个方法，通过腾讯地图给我一个本地的经纬度单做地图中心点坐标
    getPoint() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject("Geolocation is not supported by this browser.");
        }
        navigator.geolocation.getCurrentPosition((position)=> {
          const point = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          };
          resolve(point);
        }, (error)=> {
          reject(error);
        });
      });
    },
  },
}
</script>
<i18n>
{
  "zh-CN": {
    "title": "编辑电子围栏",
    "modes": {
      "drawing": "绘画模式",
      "editing": "编辑模式"
    },
    "columns": {
      "placeholder": "请输入围栏区域"
    }
  },
  "en-US": {
    "title": "Edit Electronic Fence",
    "modes": {
      "drawing": "Drawing Mode",
      "editing": "Editing Mode"
    },
    "columns": {
      "placeholder": "Please enter the fence area"
    }

  },
  "fr-FR": {
    "title": "Modifier la clôture électronique",
    "modes": {
      "drawing": "Mode Dessin",
      "editing": "Mode Édition"
    },
    "columns": {
      "placeholder": "Veuillez entrer la zone de la clôture"
    }
  }
}
</i18n>
<style scoped>
.map-tools{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>